package structure.linkedList2;

public class MySingleLinkedList {

    private Node header;
    private int size;

    // 头部插入
    public void addHeader(Integer value) {
        Node node = new Node(value);
        if (size == 0) {
            header = node;
        } else {
            node.next = header;
            header = node;
        }
        size++;
    }

    // 尾部插入
    public void addTail(Integer value) {
        Node node = new Node(value);
        if (size == 0) {
            header = node;
        } else {
            Node temp = header;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
        size++;
    }

    // 头部删除
    public void deleteNode() {
        header = header.next;
        size--;
    }

    // 根据index查询节点
    public Integer find(Integer index) throws Exception {
        if (index < 0 || index > size - 1) {
            throw new Exception();
        }
        if (index == 0) {
            return header.value;
        }
        int in = 0;
        Node node = header;
        while (node.next != null) {
            node = node.next;
            in++;
            if (in == index) {
                return node.value;
            }

        }
        return null;
    }

    // 删除某个位置的节点 - 第一性原理
    public void delete(Integer index) throws Exception {
        if (index < 0 || index > size - 1) {
            throw new Exception();
        }
        if (index == 0) {
            header = header.next;
            size--;
            return;
        }
        int in = 0;
        Node node = header;
        while (node != null && node.next != null) {
            // 0 == 1
            if (in == index - 1) {
                node.next = node.next.next;
                size--;
                break;
            }
            in++;
            node = node.next;
        }
    }

    // 某个位置插入节点 - 第一性原理
    public void insert(Integer index, Integer value) throws Exception {
        if (index < 0 || index > size - 1) {
            throw new Exception();
        }
        Node node = new Node(value);

        if (index == 0) {
            node.next = header.next;
            header = node;
            size++;
            return;
        }
        Node temp = header;
        int in = 0;
        while (in < index - 1) {
            temp = temp.next;
            in++;
        }

        node.next = temp.next;
        temp.next = node;
        size++;
    }


    // 反转单链表
    public Node reverse(Node node) {
        Node pre = null;
        Node next = null;
        while (node != null) {
            next = node.next;
            node.next = pre;
            pre = node;
            node = next;
        }
        return pre;
    }

    static class Node {
        private final Integer value;
        private Node next;

        Node(Integer value) {
            this.value = value;
        }
    }
}
